package tmi.li.txwidgets.txbtry;

import tmi.li.txwidgets.TxWidgetsFinals;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class TxBtryReceiver extends BroadcastReceiver{
	static String TAG = "tmi.li.txwidgets.txbtry.TxBtryReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {

		

		//getting the Broadcast Action to verify the intent Actions
		String action = intent.getAction();
		Log.d(TAG, "onReceive() intent => "+action);

		if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
			AppWidgetManager gm = AppWidgetManager.getInstance(context);
			int[] appWidgetIds = gm.getAppWidgetIds(new ComponentName(context.getApplicationInfo().packageName, TxWidgetsFinals.TXBTRY_WIDGET_CLASS_PATH));  

			for(int id : appWidgetIds){
				checkBatteryLevel(context, id, intent);
				TxBtryProvider.updateWidget(context, gm,  id);
			}
		}
	}

	public void checkBatteryLevel(Context context, int id, Intent intent) {
		Log.d(TAG, "checkBatteryLevel() id => "+id);

		TxBtryWidget widget = new TxBtryWidget(context);
		
		if(widget.load(id)) {
			//check for first run or if Plugged status changed
			if((widget._percent == null || widget._percent == "") ||
				widget._plug.equals(((intent.getIntExtra("plugged", 0) == 0) ? "false" : "true")) == false) {
	
				widget._percent = String.valueOf(intent.getIntExtra("level", 0));
				widget._time = String.valueOf(System.currentTimeMillis());
				widget._resttime = "0";
				widget._plug = ((intent.getIntExtra("plugged", 0) == 0) ? "false" : "true");
				Log.d(TAG, "checkBatteryLevel() first time or plug changed");
			}else {
				int startLevel = Integer.valueOf(widget._percent);
				int currentLevel = intent.getIntExtra("level", 0);
				boolean isPlugged = (intent.getIntExtra("plugged", 0) == 0) ? false : true;
				long startTime = Long.valueOf(widget._time); 
				long restTime;
				double tmp;
				//check if device is charging
				Log.d(TAG, "checkBatteryLevel() startTime => "+startTime);
				Log.d(TAG, "checkBatteryLevel() startLevel => "+startLevel);
				Log.d(TAG, "checkBatteryLevel() currentlevel => "+currentLevel);
				Log.d(TAG, "checkBatteryLevel() plug => "+isPlugged);
				if(isPlugged) {			
					restTime = 0;
				}else {
					tmp = (double)(startLevel-currentLevel);
					tmp = tmp / ((double)(System.currentTimeMillis() - startTime));
					restTime = (long)(currentLevel / tmp);
				}
				widget._percent = String.valueOf(currentLevel);
				widget._resttime = String.valueOf(restTime);
				widget._plug = ((intent.getIntExtra("plugged", 0) == 0) ? "false" : "true");
				widget._time = String.valueOf(System.currentTimeMillis());
				
			}
			widget._temp = String.valueOf(intent.getIntExtra("temperature", 0)); 
			widget.logWidget();
			widget.update();
		}
	}

}